package com.mingte.manghe.utils;

import com.mingte.manghe.costominterface.CommonConsumer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SheetUtils {

    /**
     * sheet转Map处理
     * @param sheet
     * @return
     */
    public static <T> List<T> sheetToMap(Sheet sheet, CommonConsumer<T> commonConsumer){
        if(null == sheet){
            return null;
        }
        String[] key = null;
        short lastCellNum = 0;
        List<T> list = new ArrayList<>();
        for(int i = 0; i <= sheet.getLastRowNum(); i++){
            Row row = sheet.getRow(i);
            Map<String,Object> map = null;
            if(i == 0){
                lastCellNum = row.getLastCellNum();
                key = new String[lastCellNum];
            }else{
                map = new HashMap<>(lastCellNum);
            }
            for(int j = 0; j < lastCellNum; j++){
                Cell cell = row.getCell(j);
                if(null == cell || "".equals(cell.toString())){
                    //logger.info("{}表,{}行,{}列为空",sheet.getSheetName(),i,j);
                    continue;
                }
                if(i == 0){
                    key[j] = cell.toString();
                }else{
                    map.put(key[j],cell);
                }
            }
            if(i > 0){
                T handle = commonConsumer.handle(key, map);
                list.add(handle);
            }
        }
        return list;
    }
}
